package com.fx.smsclient.modules.handle;

import com.fx.smsclient.modules.service.CallBackMsgService;
import com.zx.sms.BaseMessage;
import com.zx.sms.codec.cmpp.msg.CmppDeliverRequestMessage;
import com.zx.sms.codec.cmpp.msg.CmppDeliverResponseMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitRequestMessage;
import com.zx.sms.codec.cmpp.msg.CmppSubmitResponseMessage;
import com.zx.sms.handler.api.AbstractBusinessHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RwHandler extends AbstractBusinessHandler {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        ctx.fireChannelRead(msg);
        if (msg instanceof CmppSubmitResponseMessage) {
            CallBackMsgService.put((CmppSubmitResponseMessage)msg);
            log.info("read:{}",msg);
        }
        else if (msg instanceof CmppDeliverRequestMessage){
            CmppDeliverRequestMessage e = (CmppDeliverRequestMessage) msg;
            CmppDeliverResponseMessage responseMessage = new CmppDeliverResponseMessage(e.getHeader().getSequenceId());
            responseMessage.setResult(0);
            responseMessage.setMsgId(e.getMsgId());
            ctx.channel().writeAndFlush(responseMessage);
            CallBackMsgService.put((CmppDeliverRequestMessage)msg);
            log.info("read:{}",msg );
        }
        else {
//            logger.info("read:{}",msg);
        }
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)  {
        ctx.write(msg, promise);
        if (msg instanceof CmppSubmitRequestMessage) {
            log.info("write:{}",msg);
        } else if (msg instanceof CmppDeliverRequestMessage) {
            log.info("write:{}",msg);
        } else if (msg instanceof BaseMessage) {
//            logger.info("write:{}",msg);
        }
    }

    @Override
    public String name() {
        return "RwHandler";
    }
}
